import Vue from 'vue'
import VueRouter from 'vue-router'

// Vite项目，.vue
import Login from '@/views/login.vue'
import Register from '@/views/register.vue'
import Detail from '@/views/detail.vue'
import Layout from '@/views/layout.vue'
// 二级路由
import Like from '@/views/second/like.vue'
import Article from '@/views/second/article.vue'
import Collect from '@/views/second/collect.vue'
import User from '@/views/second/user.vue'

import { getToken } from '@/utils/storage'
import { Toast } from 'vant'
Vue.use(VueRouter)

const router = new VueRouter({
    routes: [
        { path: '/login', component: Login, name: 'Login' },
        { path: '/register', component: Register },
        { path: '/detail/:id', component: Detail },
        {
            path: '/',
            name: 'Layout',
            component: Layout,
            redirect: '/article',
            // 二级路由配置
            children: [
                { path: '/article', component: Article },
                { path: '/like', component: Like },
                { path: '/collect', component: Collect },
                { path: '/user', component: User }
            ]
        }
    ]
})

// 设置了一个白名单
const whiteList = ['/login', '/register']
// 全局前置守卫，拦截，如果没有登录，没有token，拦截到 /login
router.beforeEach((to, from, next) => {
    const token = getToken()
    console.log(token) // undefined
    if (token) {
        next() // 放行
    } else {
        if (whiteList.includes(to.path)) {
            next() // 放行
        } else {
            // 提示，你还没有登录哟
            Toast('你还没有登录哟~~')
            next('/login')
        }
    }
})

export default router
